/**
 * 
 */
package com.qunar.crawler.html;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qunar.crawler.bean.Account;
import com.qunar.crawler.bean.ProxySetting;
import com.qunar.crawler.utils.ConfigBatchInit;
import com.qunar.crawler.utils.ConfigUtils;

/**
 * @author tao.zhang
 */
public class HtmlAction {

	private static final Logger logger = LoggerFactory
			.getLogger(HtmlAction.class);

	private  HttpClient hc;

	public HtmlAction() {
		/** ----------初始化 httpClient--------- */
		hc = new HttpClient();
		hc.getHttpConnectionManager().getParams()
				.setConnectionTimeout(1000 * 120);
		hc.getHttpConnectionManager().getParams().setSoTimeout(1000 * 180);
		hc.getHostConfiguration().setHost("117go.com");
	}


	public  String get(String url) {

		GetMethod httpGet = null;
		String page = null;
		// ProxySetting ps = ConfigBatchInit.getRandomProxySetting();
		ProxySetting ps = ConfigUtils.getRandomProxySetting();
		String agent = ConfigBatchInit.getRandomAgent();
		try {
			/** ----------初始化Get---------------- */
			httpGet = new GetMethod(url);
			httpGet.setRequestHeader("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			httpGet.setRequestHeader("Accept-Language", "zh-cn");
			httpGet.setRequestHeader("Cache-Control", "max-age=0");
			httpGet.setRequestHeader("Connection", " Keep-Alive");
			httpGet.setRequestHeader("Referer", "http://117go.com/live.html");
			httpGet.setRequestHeader("User-Agent", agent);

			/** -------------发起http请求----------------- */
			logger.info("======发起http请求======");
			// if (ArrayUtils.isEmpty(hc.getState().getCookies())) {
			// Cookie[] cookies = login117Go();
			// hc.getState().addCookies(cookies);
			//
			// }

			hc.getHostConfiguration().setProxy(ps.getIp(), ps.getProt());
			//hc.getHostConfiguration().setProxy("122.72.0.145", 80);
			logger.info("login ip:" + hc.getHostConfiguration().getProxyHost()
					+ "port:" + hc.getHostConfiguration().getProxyPort());
			// logger.info("login cookie:" + hc.getState().getCookies());
			int statusCode = hc.executeMethod(httpGet);

//			while (statusCode != 200) {
//				ps = ConfigUtils.getRandomProxySetting();
//				hc.getHostConfiguration().setProxy(ps.getIp(), ps.getProt());
//				logger.info("change to new proxy:" + ps.getIp() + " prot: "
//						+ ps.getProt());
//				statusCode = hc.executeMethod(httpGet);
//			}
			logger.info("======请求状态：" + statusCode + "======");
			logger.info("======http请求结束======");

			if (statusCode == HttpStatus.SC_OK) {
				InputStream is = new BufferedInputStream(
						httpGet.getResponseBodyAsStream());
				List<Byte> list = new ArrayList<Byte>(147216);
				int read;
				while ((read = is.read()) != -1) {
					list.add((byte) read);
				}

				byte[] bs = new byte[list.size()];
				for (int i = 0; i < list.size(); i++)
					bs[i] = list.get(i).byteValue();

				String charset = "utf-8";
				page = new String(bs, charset);
			}

		} catch (HttpException e) {
			logger.error("http请求异常！");
		} catch (IOException e) {
			logger.error("http请求IO异常！");
		} finally {
			if (null != httpGet)
				httpGet.releaseConnection();
		}

		return page;
	}

	private static Cookie[] login117Go(ProxySetting ps) {
		Cookie[] cookies = null;
		try {
			HttpClient hc = new HttpClient();
			hc.getHostConfiguration().setProxy(ps.getIp(), ps.getProt());
			hc.getHostConfiguration().setHost("http://www.117go.com", 80);
			Account a = ConfigBatchInit.getAccountList().getFirst();
			// 登录开心页面
			PostMethod post = new PostMethod(
					"http://117go.com/index.php?c=user&a=loginCheck");
			NameValuePair ie = new NameValuePair("User-Agent",
					ConfigBatchInit.getRandomAgent());
			NameValuePair url = new NameValuePair("url",
					"http://117go.com/all_tour_list_p1.html");
			NameValuePair username = new NameValuePair("email", a.getEmail());
			NameValuePair password = new NameValuePair("password1",
					a.getPassword());

			post.setRequestBody(new NameValuePair[] { ie, url, username,
					password });
			post.setRequestHeader("Referer",
					"  http://www.117go.com/index.php?c=user&a=login");
			System.out
					.println("******************************登录******************************");
			hc.executeMethod(post);
			cookies = hc.getState().getCookies();
			if (null == cookies) {
				System.out
						.println("******************************登录失败****************************");
			} else {
				System.out
						.println("******************************登录成功****************************");
			}
			// hc.getState().addCookies(cookies);
			post.releaseConnection();
			return cookies;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return cookies;
	}

}
